# 用户表
{mongoose} = require "./mongodb"
User = new mongoose.Schema({
    username: String
    password: String
    salt: String
    role: String
    photo: String
    email: String
    create_date: type: Date, default: mongoose.dateHandle # 创建时间
    modify_date: type: Date, default: mongoose.dateHandle # 修改时间

});

UserModel = mongoose.model('user', User)

User = ->

 # [save description] 插入记录
User.prototype.save = (obj, callback) ->
    instance = new UserModel(obj)
    instance.save (err, obj, numberAffected) ->
        callback(err, obj, numberAffected)

# [findOne description] 按条件查找对象 返回第一个
User.prototype.findOne = (conditions, callback) ->
  # console.log "arguments size: #{arguments.length}"
  UserModel.findOne.apply UserModel, arguments

# [findOne description] 按条件查找对象 返回集合
# @param conditions 条件
# @param fields seletced字段
User.prototype.find = (conditions, fields, options, callback) ->
  UserModel.find.apply UserModel, arguments

#查询所有
User.prototype.findAll = (callback) ->
  this.find {}, callback

 # [list description] 分页查询所有记录
 # @param  {[Number]}   page      [description] 第几页
 # @param  {[Number]}   pageLimit [description] 每页限制数
 # @param  {[string]}   sortParam [description] 排序字段
User.prototype.list = (page, pageLimit, sequence, callback) ->
  if sequence
    query = UserModel.find ({})
    .select "username  role photo"
    .sort "-#{sequence}"
    .limit (pageLimit)
    .skip (page - 1 ) * pageLimit
    .exec (err, obj) ->
      callback(err, obj)
  else
    query = UserModel.find ({})
    .select "username  role photo"
    .limit (pageLimit)
    .skip (page - 1 ) * pageLimit
    .exec (err, obj) ->
      callback(err, obj)

User.prototype.findOneAndUpdate = (conditions, update, callback) ->
  # console.log "arguments size: #{arguments.length}"
  UserModel.findOneAndUpdate.apply UserModel, arguments

# [findOne description] 更新文档
# @param  {[obj]}   conditions      [description] 根据某个条件 {_id: id}，查找记录
# @param  {string} field [description] option
# @param  {[obj]} options [description] option
User.prototype.update = (conditions, field, options, callback) ->
  UserModel.update.apply UserModel, arguments

User.prototype.findOneAndRemove = (conditions, options, callback) ->
  # console.log "arguments size: #{arguments.length}"
  UserModel.findOneAndRemove.apply UserModel, arguments

# [remove description] 移除记录
# @param  {[type]}   conditions      [description] 根据某个条件 {_id: id}，删除记录
User.prototype.remove = (conditions, callback) ->
  UserModel.remove.apply pageTemplates, arguments

module.exports = new User()
